<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>

  <script>
    // 生成器函数
    function* foo() {
      console.log("111");
      yield "Hello";
      console.log("222");
      yield "World";
      console.log("333");
      yield "codewhy"
    }

    // iterator: 迭代器
    const result = foo();
    console.log(result);

    // 使用迭代器
    // 调用一次next，就会消耗一次迭代器
    const res1 = result.next()
    console.log(res1);

    const res2 = result.next()
    console.log(res2);

    const res3 = result.next()
    console.log(res3);

    const res4 = result.next()
    console.log(res4);



    // 生成器函数：依次生成1-10的数字
    function* generatorNumber() {
      for (let i = 1; i < 10; i++) {
        yield i;
      }
    }

    const numIt = generatorNumber();
    console.log(numIt.next().value);
    console.log(numIt.next().value);
    console.log(numIt.next().value);
    console.log(numIt.next().value);
    console.log(numIt.next().value);


    // generator和Promise一起来使用
    function* bar() {
      console.log("111");
      const result = yield new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve("Hello Generator");
        }, 3000);
      })
      console.log(result);
    }

    const it = bar();
    it.next().value.then(res => {
      it.next();
    })

  </script>

</body>

</html>